#include <QtGui>

#include "nconfig.h"
#include "nmusicfile.h"
#include "nmainwindow.h"

NMainWindow::NMainWindow() : tableView(this){
    setMinimumSize(QSize(320, 240));
    setWindowTitle(tr("Konvid"));

    createMenus();
    createToolbar();
    statusBar()->showMessage(tr("Ready."));
    
    setCentralWidget(&tableView);

    tableView.setModel(&tableModel);
    tableView.setColumnWidth(0, 160);
    tableView.horizontalHeader()->setStretchLastSection(true);
        
    QItemSelectionModel *sel = tableView.selectionModel();
        
    connect(sel, SIGNAL(currentChanged(const QModelIndex &, const QModelIndex &)),
	     &tableModel, SLOT(sSelectedRowChanged(const QModelIndex &, const QModelIndex &)));
    connect(&tableModel, SIGNAL(selectedSongChanged(NMusicFile *)),
	    this, SLOT(selectSong(NMusicFile *)));
    
    readSettings();
}

NMainWindow::~NMainWindow(){
    
}

/* private */

void NMainWindow::writeSettings() {
     QSettings settings;

     settings.beginGroup("MainWindow");
     settings.setValue("size", size());
     settings.setValue("pos", pos());
     settings.endGroup();
 }

 void NMainWindow::readSettings() {
     QSettings settings;

     settings.beginGroup("MainWindow");
     resize(settings.value("size", QSize(640, 480)).toSize());
     move(settings.value("pos", QPoint(200, 200)).toPoint());
     settings.endGroup();
 }

void NMainWindow::createMenus() {
    QMenu *menu, *subMenu;
    
    menu = menuBar()->addMenu(tr("&File"));
    menu->addAction(QIcon(":/images/menu/mopen"), tr("&Open..."), this, SLOT(sOpen()), tr("Ctrl+O"));
    menu->addAction(QIcon(":/images/menu/mimport"), tr("&Import..."), this, SLOT(sImport()), tr("Ctrl+I"));
    menu->addSeparator();
    menu->addAction(tr("&Clear"), this, SLOT(sClear()), tr("Ctrl+D"));
    menu->addAction(QIcon(":/images/menu/msaveall"), tr("Save &All..."), this, SLOT(sSaveAll()), tr("Ctrl+S"));
    menu->addSeparator();
    menu->addAction(QIcon(":/images/menu/mexit"), tr("&Exit..."), qApp, SLOT(quit()), tr("Ctrl+Q"));

    menu = encodingMenu = menuBar()->addMenu(tr("&Encoding"));
    menu->addAction(tr("&UTF8"), this, SLOT(sEncUTF8()));

    subMenu = menu->addMenu(tr("&Chinese"));
    subMenu->addAction(tr("GB2312"), this, SLOT(sEncGB2312()));
    subMenu->addAction(tr("GBK"), this, SLOT(sEncGBK()));
    subMenu->addAction(tr("GB18030"), this, SLOT(sEncGB18030()));
    subMenu->addAction(tr("BIG5"), this, SLOT(sEncBIG5()));
    subMenu->addAction(tr("BIG5-HKSCS"), this, SLOT(sEncBIG5HKSCS()));

    subMenu = menu->addMenu(tr("&Japanese"));
    subMenu->addAction(tr("Shift-JIS"), this, SLOT(sEncShiftJIS()));
    subMenu->addAction(tr("ISO 2022-JP"), this, SLOT(sEncISO2022JP()));
    subMenu->addAction(tr("EUC-JP"), this, SLOT(sEncEUCJP()));

    menu = viewMenu = menuBar()->addMenu(tr("&View"));
    
    menu = menuBar()->addMenu(tr("&Help"));
    menu->addAction(QIcon(":/images/menu/mmanual"), tr("Konvid &Handbook"), this, SLOT(sHandbook()), tr("F1"));
    menu->addSeparator();
    menu->addAction(QIcon(":/images/menu/mabout"), tr("&About..."), this, SLOT(sAbout()));
    menu->addAction(tr("About &Qt..."), qApp, SLOT(aboutQt()));
}

void NMainWindow::createToolbar(){
    QToolBar *toolBar = addToolBar(tr("Tool"));
    toolBar->setMovable(false);
    toolBar->setIconSize(QSize(22, 22));
    toolBar->addAction(QIcon(":/images/toolbar/topen"), tr("Open"), this, SLOT(sOpen()));
    toolBar->addAction(QIcon(":/images/toolbar/timport"), tr("Import"), this, SLOT(sImport()));
    toolBar->addSeparator();
    toolBar->addAction(QIcon(":/images/toolbar/tsaveall"), tr("Save All"), this, SLOT(sSaveAll()));
    toolBar->addAction(QIcon(":/images/toolbar/tclear"), tr("Clear"), this, SLOT(sClear()));
    toolBar->addSeparator();
    
    QToolButton *btn = new QToolButton;
    btn->setIcon(QIcon(":/images/toolbar/tencodings"));
    btn->setText(tr("Encodings"));
    btn->setToolTip(tr("Encodings"));
    btn->setMenu(encodingMenu);

    toolBar->addWidget(btn);
    viewMenu->addAction(toolBar->toggleViewAction());
}

void NMainWindow::setEncoding(int x){    
    tableModel.setEncoding(x);
    updateEncodingInfo();
}

void NMainWindow::updateEncodingInfo() const{    
    QString encodingName = QTextCodec::codecForMib(tableModel.encoding())->name();
    
    statusBar()->showMessage(tr("Currently selected encoding: %1.").arg(encodingName));
}

void NMainWindow::closeEvent(QCloseEvent *event){
    Q_UNUSED(event);
    writeSettings();
}

/* private slots */

void NMainWindow::sEncUTF8(){ setEncoding(106); }
void NMainWindow::sEncGB2312(){ setEncoding(2025); }
void NMainWindow::sEncGBK(){ setEncoding(113); }
void NMainWindow::sEncGB18030(){setEncoding(114); }
void NMainWindow::sEncBIG5(){setEncoding(2026); }
void NMainWindow::sEncBIG5HKSCS(){setEncoding(2101); }

void NMainWindow::sEncShiftJIS(){setEncoding(17);}
void NMainWindow::sEncISO2022JP(){ setEncoding(39);}
void NMainWindow::sEncEUCJP(){ setEncoding(18);}

void NMainWindow::sOpen(){
    QString homePath = QDir::toNativeSeparators(QDir::homePath());
    QStringList fileNames = QFileDialog::getOpenFileNames(this,
						    tr("Please select one music file"),
						    homePath,
						    tr("Music files ( *.mp3 );;All files (*.*)"));
					
    tableModel.addFiles(fileNames);
}

void NMainWindow::sImport(){
    QFileDialog dialog(this);
    dialog.setDirectory(QDir::homePath());
    dialog.setFileMode(QFileDialog::DirectoryOnly);
    dialog.setNameFilter(tr("Directories (*.*)"));
    dialog.setWindowTitle(tr("Please select a folder"));
    
    QStringList fileNames;
    if (!dialog.exec()) return;

    fileNames = dialog.selectedFiles();
    if(fileNames.empty()) return;
    
    QDir dir(fileNames.first());
    dir.setNameFilters(QStringList("*.mp3"));
    dir.setFilter(QDir::NoSymLinks | QDir::Files);
    
    QStringList fileLists;
    
    fileNames = dir.entryList();
    QStringList::const_iterator iter;
    for (iter = fileNames.constBegin(); iter != fileNames.constEnd();    ++iter)
	fileLists << (dir.absolutePath() + QDir::toNativeSeparators("/") + (*iter));
    
    tableModel.addFiles(fileLists);
}

void NMainWindow::sClear(){
    if(tableModel.recordsCount() == 0) return;

    tableModel.clear();
    updateEncodingInfo();
}

void NMainWindow::sSaveAll(){
    if(tableModel.recordsCount() == 0) return;

    QString encodingName = QTextCodec::codecForMib(tableModel.encoding())->name();
    
    QMessageBox msgBox;
    msgBox.setText(tr("Konvid is about to convert the encoding to %1. This operation, once completed, cannot be undone.").arg(encodingName));
    msgBox.setInformativeText(tr("Are you sure this is what you want?"));
    msgBox.setWindowTitle(tr("Confirmation"));
    msgBox.setStandardButtons(QMessageBox::Ok | QMessageBox::Cancel);
    msgBox.setDefaultButton(QMessageBox::Ok);
    msgBox.setIcon(QMessageBox::Warning);
    int res = msgBox.exec();
    
    if(res == QMessageBox::Cancel) return;
    
    tableModel.saveAll();
    sClear();
    statusBar()->showMessage(tr("Conversion completed."));
}

void NMainWindow::sHandbook(){    
    QDesktopServices::openUrl(QUrl("http://nlyrics.7do.net/konvid"));
}

void NMainWindow::sAbout(){ 
    #ifdef N_PHONON
    QString edition(tr("full"));
    #else
    QString edition(tr("lite"));
    #endif
    
    QMessageBox::about(this, 
    tr("About"), 
    tr("<b>Konvid %1 %2 </b> MP3 tag encoding converter<br/>Built on %3<br/><br/>").arg(edition).arg(KONVID_VERSION).arg(BUILT_DATE)+
    tr("Author: nanmus, Jianxin Zhong<br/>For more information, please visit: <a href=\"http://nlyrics.7do.net/konvid\">http://nlyrics.7do.net/konvid</a>"));
}

void NMainWindow::selectSong(NMusicFile *x){
    statusBar()->showMessage(x->path());
}